﻿using LinqToTwitter;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Q42.WinRT.Data;
using SpaceNeedle.SDK.Windows.Platform.Commands;
using SpaceNeedle.SDK.Windows.Platform.Data;
using SpaceNeedle.SDK.WindowsPhone;
using SpaceNeedle.x6473.WindowsPhone.Common;
using SpaceNeedle.x6473.WindowsPhone.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace SpaceNeedle.x6473.WindowsPhone.ViewModels
{
    public class SocialViewModel : GlobalViewModel
    {
        public SocialViewModel() :base()
        {
            this.LoadCommand = new RelayCommand(Load);
            this.PostDetailsCommand = new RelayCommand(PostDetails);
            this.TwitterDetailsCommand = new RelayCommand(TwitterDetails);
        }

        public AppContent.SocialInfo StaticContent
        {
            get { return this.Get<AppContent.SocialInfo>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<Post> FacebookPosts
        {
            get { return this.Get<ObservableCollection<Post>>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<Post> TwitterPosts
        {
            get { return this.Get<ObservableCollection<Post>>(); }
            set { this.Set(value); }
        }

        protected async override void Load()
        {
            this.FacebookPosts = new ObservableCollection<Post>();
            this.TwitterPosts = new ObservableCollection<Post>();

            this.IsInProgress = true;

            await base.LoadAsync();

            this.StaticContent = this.AppContent.Social;

            string fanpage = StaticContent.FacebookUrl;
            WebRequest client = new WebRequest();

            string oauthUrl = string.Format("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={0}&client_secret={1}", "218336355033893", "55c52366e3dd9a46ebf7760776ddcc56");

            string accessToken = string.Empty;
            
            string completeAccessToken = await client.DownloadStringAsync(oauthUrl);

            if (!string.IsNullOrEmpty(completeAccessToken))
            {
                string[] tokenFragments = completeAccessToken.Split('=');

                if (tokenFragments.Length >= 2)
                {
                    accessToken = tokenFragments[1];
                }
            }

            if (string.IsNullOrEmpty(accessToken))
            {
                Get<Exception>();
            }

            var info = await SpaceNeedle.x6473.WindowsPhone.Common.Facebook.GetPage(fanpage);

            if (info == null)
            {
                return;
            }

            string pageFeed = await client.DownloadStringAsync( string.Format("https://graph.facebook.com/{0}/feed?access_token={1}", fanpage, accessToken));
            string pagePosts = await client.DownloadStringAsync(string.Format("https://graph.facebook.com/{0}/posts?access_token={1}&fields=id,object_id,message,picture,type,likes.limit(1).summary(true)", fanpage, accessToken));

            JArray posts = JObject.Parse(pagePosts)["data"] as JArray;
            int postIndex = 0;
            JObject post = null;

            if (posts == null)
            {
                return;
            }

            List<JObject> validPosts = new List<JObject>();

            foreach (var p in posts)
            {
                post = posts[postIndex++] as JObject;

                if (post != null && post["type"].Value<string>() == "photo")
                {
                    validPosts.Add(post);
                }
            }

            JObject photo = null;

            foreach (var oPost in validPosts)
            {
                photo = await GetFacebookPostPhoto(oPost["object_id"].Value<string>(), accessToken);

                if (photo == null)
                {
                    return;
                }

                if(oPost["message"] == null)
                {

                }
                else
                {
                    oPost["postImage"] = photo["source"];
                    oPost["postText"] = photo["name"];

                    this.FacebookPosts.Add(new Post() { Text = oPost["message"].ToString(), Thumbnail = new Uri(oPost["picture"].ToString()), Photo = new Uri(photo["source"].ToString()) });
                }
            }

            //Twitter
            Exception exception = null;
            try
            {
                var twitter = new LinqToTwitter.TwitterContext(await SocialViewModel.AuthorizeOnTwitter());

                string twProfile = StaticContent.TwitterUrl;

                var tweets =
                await
                (from tweet in twitter.Status
                 where tweet.Type == StatusType.User &&
                       tweet.ScreenName == twProfile
                 select tweet)
                .ToListAsync();

                foreach (var tweet in tweets)
                {
                    this.TwitterPosts.Add(new Post() { TwitterPost = tweet.Text.ToString() });
                }
            }

            catch (Exception ex)
            {
                exception = ex;
            }

            Tracking.SendView(ViewsNames.Social);

            this.IsInProgress = false;
        }

        public ICommand PostDetailsCommand { get; set; }

        private void PostDetails(object param)
        {
            if (param == null)
            {
                return;
            }

            AppViewModel.Instance.Properties.SelectedPost = param as Post;
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.FacebookPostDetail);
        }

        public ICommand TwitterDetailsCommand { get; set; }

        private void TwitterDetails(object param)
        {
            if (param == null)
            {
                return;
            }

            AppViewModel.Instance.Properties.SelectedPost = param as Post;
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.TwitterPostDetail);
        }

        private async Task<JObject> GetFacebookPostPhoto(string id, string accessToken)
        {
            WebRequest client = new WebRequest();
            string photoInfo = await client.DownloadStringAsync(string.Format("https://graph.facebook.com/{0}?access_token={1}", id, accessToken));
            return JObject.Parse(photoInfo);
        }

        public async static Task<LinqToTwitter.IAuthorizer> AuthorizeOnTwitter()
        {
            //Dev
            string consumerKey = "IlQldn0SKgwRXIhaIPa89w";
            string consumerSecret = "wHFUEkGROdl1JxDH2a9iSTwcUDqZ24nPu898MlOrM";

            LinqToTwitter.ApplicationOnlyAuthorizer authorizer = null;

            authorizer = new LinqToTwitter.ApplicationOnlyAuthorizer()
            {
                CredentialStore = new LinqToTwitter.InMemoryCredentialStore()
                {
                    ConsumerKey = consumerKey,
                    ConsumerSecret = consumerSecret
                },
                //UseCompression = true
            };

            await authorizer.AuthorizeAsync();

            return authorizer;
        }
    }
}
